package com.honglu.shiro;


import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import com.honglu.backend.bo.MenuBo;
import com.honglu.backend.bo.UUserBo;
import com.honglu.backend.service.impl.MenuServiceImpl;
import com.honglu.backend.service.impl.UUserServiceImpl;

/**
 * shiro身份校验核心类
 * 
 */

public class MyShiroRealm extends AuthorizingRealm {
	
	private static Logger logger=Logger.getLogger(MyShiroRealm.class);

	@Autowired
	private UUserServiceImpl userServiceImpl;
	
	@Autowired
	private MenuServiceImpl menuServiceImpl;
	

	/**
	 * 登录验证
	 * 认证信息.(身份验证) : Authentication 是用来验证用户身份
	 * 重写doGetAuthenticationInfo方法，调用数据库匹配帐号密码
	 *  
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		logger.info("身份认证方法：MyShiroRealm.doGetAuthenticationInfo()");
		ShiroToken token = (ShiroToken) authcToken;
		Map<String, Object> map = new HashMap<String, Object>();  
		map.put("userName", token.getUsername());
		map.put("password", token.getPswd());
//		UUserBo user = null;
		// 从数据库获取对应用户名密码的用户
		UUserBo user = userServiceImpl.selectByMap(map);
		 
		if (null == user) {
			throw new AccountException("帐号或密码不正确！");
		}else if(user.getState() == 0){
			/**
			 * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
			 */
			throw new DisabledAccountException("帐号已经禁止登录！");
		}else{
			//更新登录时间 last login time， 已经写到LoginController里
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
	}
	
	
	

	/**
	 * 	权限验证
	* 	授权URL
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		System.out.println("权限认证方法：MyShiroRealm.doGetAuthorizationInfo()");
		UUserBo token = (UUserBo)SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		
		
		MenuBo Menu = new MenuBo();
		Menu.setRoleId(token.getRoleId().toString());// 获取角色id
		List<MenuBo> list = menuServiceImpl.getMenuRoleAll(Menu);// 拿到权限
		Set<String> permissionSet = new HashSet<String>();
		for (MenuBo menuBo : list) {
			permissionSet.add(menuBo.getTitle().trim());
		}
		info.setStringPermissions(permissionSet);
	    return info;
	    
	}
	
	
	
	
	
//	/**
//	 * 	权限验证
//	* 	授权URL
//	 */
//	@Override
//	protected AuthorizationInfo doGetAuthorizationInfo(
//			PrincipalCollection principals) {
//		System.out.println("权限认证方法：MyShiroRealm.doGetAuthorizationInfo()");
//		UUserBo token = (UUserBo)SecurityUtils.getSubject().getPrincipal();
//		Integer userId = token.getId();
//		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
//		//根据用户ID查询角色（role），放入到Authorization里。
//		/*Map<String, Object> map = new HashMap<String, Object>();
//		map.put("user_id", userId);
//		List<SysRole> roleList = sysRoleService.selectByMap(map);
//		Set<String> roleSet = new HashSet<String>();
//		for(SysRole role : roleList){
//			roleSet.add(role.getType());
//		}*/
//		//实际开发，当前登录用户的角色和权限信息是从数据库来获取的，我这里写死是为了方便测试
////		Set<String> roleSet = new HashSet<String>();
////		roleSet.add("12");
////		info.setRoles(roleSet);
//		//根据用户ID查询权限（permission），放入到Authorization里。
//		/*List<SysPermission> permissionList = sysPermissionService.selectByMap(map);
//		Set<String> permissionSet = new HashSet<String>();
//		for(SysPermission Permission : permissionList){
//			permissionSet.add(Permission.getName());
//		}*/
////		Set<String> permissionSet = new HashSet<String>();
////		permissionSet.add("权限添加");
////		info.setStringPermissions(permissionSet);
//	    return info;
//	}
}
